package com.yixia.system.service.impl.system;

import cn.hutool.core.convert.Convert;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yixia.common.annotation.DataScope;
import com.yixia.common.core.domain.TreeSelect;
import com.yixia.common.core.domain.entity.SysDept;
import com.yixia.common.core.domain.entity.SysRole;
import com.yixia.common.core.domain.entity.SysUser;
import com.yixia.common.utils.SecurityUtils;
import com.yixia.common.utils.StringUtils;
import com.yixia.system.mapper.system.SysDeptMapper;
import com.yixia.system.mapper.system.SysRoleMapper;
import com.yixia.system.mapper.system.SysUserMapper;
import com.yixia.system.service.system.SysDeptService;
import com.yixia.common.constant.UserConstants;
import com.yixia.common.exception.ServiceException;

import com.yixia.common.utils.spring.SpringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 35038
* @description 针对表【sys_dept(部门表)】的数据库操作Service实现
* @createDate 2023-07-10 22:01:45
*/
@Slf4j
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept>
    implements SysDeptService {

    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Override
    public List<TreeSelect> selectDeptTreeList(SysDept dept) {
        /*先根据dept来获取相关的depts信息，查询时注意范围*/
        /*获取一个aop代理对象*/
        List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);/*先获取部门信息*/
        return buildDeptTreeSelect(depts);
    }

    /**
     * COMMIT: 完成
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "sys_dept", deptField = "dept_id")
    public List<SysDept> selectDeptList(SysDept dept)
    {
        return deptMapper.selectDeptList(dept);
    }

    /**
     * 判断部门名是否存在
     * @param dept
     * @return
     */
    @Override
    public boolean checkDeptNameUnique(SysDept dept) {

        //看是修改还是添加
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        //根据用部门名获取部门信息
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotNull(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName());
        SysDept info = getOne(queryWrapper);
        //找到了，但查找值的id与传入的id不相等，不能添加，不能修改
        if(StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()){
            return false;
        }
        return true;
    }


    /**
     * 新增部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        //先查找要添加的父节点的状态
        SysDept info = deptMapper.selectById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus()))
        {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insert(dept);
    }


    /**
     * 看当前登录者是否有权限访问部门信息
     */
    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())){
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if(StringUtils.isEmpty(depts)){
                throw new ServiceException("没有权限访问部门数据!");
            }
        }
    }


    /**
     * 根据id获取部门的信息
     * @param deptId
     * @return
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        SysDept deptById = this.getById(deptId);
        /*将其父部门的名称查出来并封装到对象中*/
        SysDept byIdParent = this.getById(deptById.getParentId());
        if(StringUtils.isNotNull(byIdParent)) {
            deptById.setParentName(byIdParent.getDeptName());
        }
        return deptById;
    }


    /**
     * 查看该部门中是否含有子部门
     * @param deptId
     * @return
     */
    @Override
    public boolean hasChildByDeptId(Long deptId) {
        return deptMapper.hasChildByDeptId(deptId);
    }


    /**
     * 查看该部门中是否还有用户
     * @param deptId
     * @return
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getDeptId, deptId);
        queryWrapper.eq(SysUser::getDelFlag, '0');/*确保用户没有被删除*/
        List<SysUser> list = userMapper.selectList(queryWrapper);
        return list.size() > 0;
    }


    /**
     * 根据id来删除部门
     * @param deptId
     * @return
     */
    @Override
    public boolean deleteDeptById(Long deptId) {
        LambdaUpdateWrapper<SysDept> updateWrapper = new LambdaUpdateWrapper<>();
        // 设置需要更新的条件，这里使用部门ID作为条件
        updateWrapper.eq(SysDept::getDeptId, deptId)
                .set(SysDept::getDelFlag, "2");
        // 调用update方法进行部门删除标志的更新,根据更新的结果返回布尔值
        return this.update(updateWrapper);
    }


    /**
     * 修改部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int updateDept(SysDept dept) {

       /* SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = deptMapper.selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;*/

        // 查询出要修改的部门的父亲部门的信息和要修改的部门的信息
        SysDept newParentDept = deptMapper.selectById(dept.getParentId());
        SysDept oldDept = deptMapper.selectById(dept.getDeptId());
        // 新的父部门存在，并且旧的部门也才存在对新该要修改的部门及该部门一下的部门的父结构进行修改
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        // 修改要修改的部门信息
        int result = deptMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors()))
        {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;

       /* if(dept.getParentId() == 0L && Objects.equals(oldDept.getDeptId(), dept.getDeptId())){
            *//*要修改的是根部门---直接进行修改即可*//*
            return updateById(dept);
        }

        //1.先将该部门的父部门查找出来newParentDept
        SysDept newParentDept = this.selectDeptById(dept.getParentId());

        //3.newParentDept和oldDept都不为空，对newAncestors进行拼接
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept))
        {
            String newAncestors = newParentDept.getAncestors() + ",[" + newParentDept.getDeptId() + "]";
            String oldAncestors = oldDept.getAncestors();*//*原来的祖籍信息*//*
            dept.setAncestors(newAncestors);*//*将新的祖籍信息存入dept*//*
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);*//*修改子元素之间关系*//*
        }
        int result = deptMapper.updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors())){
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }

        return result > 0;*/
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors)
    {

        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(children);
        }

        /*通过deptId查询祖籍中包含有要，修改数据deptId的数据*//*
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.apply("find_in_set({0}, ancestors)", "[" + deptId + "]");
        List<SysDept> children = this.list(queryWrapper);
        for (SysDept child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors.replace("[", "\\[").replace("]", "\\]"), newAncestors));
        }
        if (children.size() > 0)
        {
            deptMapper.updateDeptChildren(children);//修改子元素关系
        }*/
    }


    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept)
    {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        deptMapper.updateDeptStatusNormal(deptIds);

      /*  String ancestors = dept.getAncestors();*//*获取祖籍数组*//*
        String numbersStr = ancestors.replaceAll("\\[|\\]", "");
        Long[] deptIds = Convert.toLongArray(numbersStr);
        LambdaUpdateWrapper<SysDept> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(SysDept::getStatus, "0").in(SysDept::getDeptId,  deptIds);

        // 调用 MyBatis Plus 提供的方法执行更新操作
        int updatedRows = deptMapper.update(null, updateWrapper);*/

    }



    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId)
    {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDept::getStatus, 0)
                .eq(SysDept::getDelFlag, "0")
                .apply("find_in_set({0}, ancestors)",  deptId);
        return Math.toIntExact(deptMapper.selectCount(queryWrapper));
    }

    //////////////////////////////////////////////////////////////////////////////////
    /*树表的生成*/

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts)
    {
        List<SysDept> deptTrees = buildDeptTree(depts);/*向将对象构建成树型*/
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());/*再将对象树转换成前端树*/
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    @Override
    public List<SysDept> buildDeptTree(List<SysDept> depts)
    {
        List<SysDept> returnList = new ArrayList<SysDept>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts)
        {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId()))
            {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 获取所有的部门信息
     * @return
     */
    @Override
    public List<SysDept> selectDeptAll() {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDept::getDelFlag, '0');
        return this.list(queryWrapper);
    }

    /**
     * 根据角色ID查询部门树信息
     *
     * @param roleId 角色ID
     * @return 选中部门列表
     */
    public List<Long> selectDeptListByRoleId(Long roleId){
        SysRole role = roleMapper.selectRoleById(roleId);
        return deptMapper.selectDeptListByRoleId(roleId, role.isDeptCheckStrictly());
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t)
    {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t)
    {
        List<SysDept> tlist = new ArrayList<SysDept>();
        Iterator<SysDept> it = list.iterator();
        while (it.hasNext())
        {
            SysDept n = (SysDept) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t)
    {
        return getChildList(list, t).size() > 0;
    }

}




